package reflect;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 在反射机制中判定是否有被某个注解标注的类
 */
public class ReflectDemo7 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        File dir = new File(
           ReflectDemo7.class.getResource(".").toURI()
        );
        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for(File file : subs){
            String fileName = file.getName();
            String className = fileName.substring(0,fileName.indexOf("."));
            Class cls = Class.forName("reflect."+className);
            //判断当前类是否被注解@AutoRunClass标注过
//            boolean tf = cls.isAnnotationPresent(AutoRunClass.class);
//            System.out.println(className+"是否被标注:"+tf);
            if(cls.isAnnotationPresent(AutoRunClass.class)){
                //对被AutoRunClass标注过的类进行实例化
                Object obj = cls.newInstance();
                //获取当前类定义的所有方法
                Method[] methods = cls.getDeclaredMethods();
                for(Method method : methods){
                    //判断当前方法是否被@AutoRun标注过
                    if(method.isAnnotationPresent(AutoRun.class)){
                        //通过方法对象获取标注该方法的注解AutoRun
                        AutoRun ar = method.getAnnotation(AutoRun.class);
                        //获取该注解的参数   @AutoRun(3)
                        int value = ar.value();
                        System.out.println("@AutoRun("+value+")");
                        System.out.println("自动调用"+cls.getName()+"的方法"+method.getName()+"()");
                        //执行该方法
                        method.setAccessible(true);
                        for(int i=0;i<value;i++) {
                            method.invoke(obj);
                        }
                    }
                }
            }

        }
    }
}
